package com.rj.framework.workflow;

import com.rj.framework.component.ComponentRegistry;
import com.rj.framework.context.DefaultGlobalContext;
import com.rj.framework.context.GenericContext;
import com.rj.framework.context.GlobalContext;
import com.rj.framework.context.UserContext;
import com.rj.framework.transformer.TransformationRegistry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工作流引擎
 */
public class WorkflowEngine<G extends GlobalContext> {
    private final ComponentRegistry componentRegistry;
    private final TransformationRegistry transformationRegistry;
    private final Map<String, WorkflowDefinition<?, ?>> workflows = new ConcurrentHashMap<>();

    public WorkflowEngine(ComponentRegistry componentRegistry,
                          TransformationRegistry transformationRegistry) {
        this.componentRegistry = componentRegistry;
        this.transformationRegistry = transformationRegistry;
    }

    public <I, O> void registerWorkflow(String name, WorkflowDefinition<I, O> workflow) {
        workflows.put(name, workflow);
    }

    public <I, O> O executeWorkflow(String workflowName, I input, UserContext userContext) {
        DefaultGlobalContext globalContext = new DefaultGlobalContext(userContext);
        GenericContext<G> context = new GenericContext<>((G) globalContext);
        context.setInput(input);

        @SuppressWarnings("unchecked")
        WorkflowDefinition<I, O> workflow = (WorkflowDefinition<I, O>) workflows.get(workflowName);
        if (workflow == null) {
            throw new IllegalArgumentException("Workflow not found: " + workflowName);
        }

        return workflow.execute(input, context);
    }
}